﻿using CloudFranceTriple.Models;
using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;

namespace CloudFranceTriple.WebRole.Areas.Forum.Controllers
{
    public class ForumController : BaseController
    {
        private cloudfrAboq2RsDMEntities db = new cloudfrAboq2RsDMEntities();

        private readonly IWebSecurityWrapper _webSecurity;
        public ForumController()
        {
            this._webSecurity = new WebSecurityWrapper();
        }

        public ForumController(IWebSecurityWrapper webSecurity)
            : base(webSecurity)
        {
            this._webSecurity = webSecurity;
        }
        //
        // GET: /Forum/Forum/

        [AllowAnonymous()]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Index()
        {
            // Vérifier si l'utilisateur a des messages non-lus ?
            Int32 UnReadPostNumber;
            if (!User.Identity.IsAuthenticated)
            {
                ViewBag.HasForumPostUnread = false;
                UnReadPostNumber = 0;
            }
            else
            {
                UnReadPostNumber = base.ForumPostUnread.Count();
                ViewBag.HasForumPostUnread = ((UnReadPostNumber > 0) && (!UnreadMessageController._UserMarkingAllAsRead.Contains(UserId))) as Boolean?;
            }

            // Renseignements en pied de page

            //Les membres ont postés un total de 9589 messages 
            //Il y a 57 utilisateurs enregistrés 
            //Le dernier membre inscrit est [KaoS]BolT_ThroweR_86  

            //Utilisateurs actuellement connectés CaptainMagicAA  
            //Le plus grand nombre d'utilisateurs en ligne est 10 utilisateurs le 19/10/2012 21:29:54  

            var TotalPost = String.Format(CloudFranceTriple.WebRole.Properties.Resources.ForumTotalPostTitle, db.ForumPostSet.Count().ToString());
            var UserCount = String.Format(CloudFranceTriple.WebRole.Properties.Resources.ForumUserCount, db.UserProfile.Where(ul => ul.ShowInNonAdminList).Count().ToString());

            String LastRegistredUser = String.Empty;
            if (db.UserProfile.Where(ul => ul.ShowInNonAdminList).Count() > 0)
                LastRegistredUser = String.Format(CloudFranceTriple.WebRole.Properties.Resources.ForumLastRegistredUser, db.UserProfile.Find(db.UserProfile.Where(ul => ul.ShowInNonAdminList).Max(up => up.UserId)).UserName);

            var userContext = new CloudFranceTriple.WebRole.Models.UsersContext();
            var _ConnectedUsers = new StringBuilder();
            int _ConnectedUsersNumber = 0;
            var members = userContext.UserProfiles.Where(ul => ul.ShowInNonAdminList).OrderByDescending(user => user.LastRequestDate);
            foreach (CloudFranceTriple.WebRole.Models.UserProfile u in members)
            {
                var _LastRequestInMinutes = DateTime.UtcNow.Subtract(u.LastRequestDate).TotalMinutes;
                if (_LastRequestInMinutes <= Membership.UserIsOnlineTimeWindow)
                {
                    _ConnectedUsers.Append(String.Format("{0} ", u.UserName));
                    _ConnectedUsersNumber++;
                }
            }
            var ConnectedUsers = String.Format(CloudFranceTriple.WebRole.Properties.Resources.ForumConnectedUsers, _ConnectedUsers.ToString());

            var MaxConnectedUserNumber = Int32.Parse(db.ApplicationSettingSet.Where(ap => ap.Name == "MaximumOnlineUsers").First().Value);
            String MaxConnectedUserDate;

            if (_ConnectedUsersNumber >= MaxConnectedUserNumber)
            {
                MaxConnectedUserNumber = _ConnectedUsersNumber;
                MaxConnectedUserDate = DateTime.UtcNow.ToString();

                var appSetting = db.ApplicationSettingSet.Where(ap => ap.Name == "MaximumOnlineUsers").First();
                appSetting.Value = MaxConnectedUserNumber.ToString();
                db.Entry(appSetting).State = EntityState.Modified;

                appSetting = db.ApplicationSettingSet.Where(ap => ap.Name == "MaximumOnlineDate").First();
                appSetting.Value = MaxConnectedUserDate;
                db.Entry(appSetting).State = EntityState.Modified;

                db.SaveChanges();
            }
            else
            {
                MaxConnectedUserDate = db.ApplicationSettingSet.Where(ap => ap.Name == "MaximumOnlineDate").First().Value;
            }

            var MaxConnectedUser = String.Format(CloudFranceTriple.WebRole.Properties.Resources.ForumMaxConnectedUser, MaxConnectedUserNumber, MaxConnectedUserDate);
            ViewBag.ForumFooter = MvcHtmlString.Create(String.Format("<p>{0}<br />{1}<br />{2}</p><p>{3}<br />{4}</p>", TotalPost, UserCount, LastRegistredUser, ConnectedUsers, MaxConnectedUser));
            // Fin Renseignements en pied de page

            //Liste des forums autorisés pour l'utilisateur courant
            var forumIdAllowed = base.ForumIdAllowed;
            var query = db.ForumSet.Where(f1 => forumIdAllowed.Contains(f1.Id)).OrderBy(f => f.OrderForum).Include("ForumCategorySet");//.Include("ForumCategorySet.ForumTopicSet");

            return View(query.ToList());
        }

        //
        // GET: /Forum/Forum/Create

        [Authorize(Roles = "RoleAdminForum")]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Forum/Forum/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "RoleAdminForum")]
        public ActionResult Create(ForumSet forumset)
        {
            if (ModelState.IsValid)
            {
                if (db.ForumSet.Count() == 0)
                    forumset.OrderForum = 10;
                else
                    forumset.OrderForum = db.ForumSet.Max(f1 => f1.OrderForum) + 10;

                db.ForumSet.Add(forumset);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(forumset);
        }

        //
        // GET: /Forum/Forum/Edit/5

        [Authorize(Roles = "RoleAdminForum")]
        public ActionResult Edit(int id = 0)
        {
            ForumSet forumset = db.ForumSet.Find(id);
            if (forumset == null)
            {
                return HttpNotFound();
            }
            return View(forumset);
        }

        //
        // POST: /Forum/Forum/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "RoleAdminForum")]
        public ActionResult Edit(ForumSet forumset)
        {
            if (ModelState.IsValid)
            {
                db.Entry(forumset).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(forumset);
        }

        //
        // GET: /Forum/Forum/Delete/5

        [Authorize(Roles = "RoleAdminForum")]
        public ActionResult Delete(int id = 0)
        {
            ForumSet forumset = db.ForumSet.Find(id);
            if (forumset == null)
            {
                return HttpNotFound();
            }
            return View(forumset);
        }

        //
        // POST: /Forum/Forum/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "RoleAdminForum")]
        public ActionResult DeleteConfirmed(int id)
        {
            ForumSet forumset = db.ForumSet.Find(id);

            if (forumset.OrderForum < db.ForumSet.Max(f1 => f1.OrderForum))
            {
                var forumToMoveDown = db.ForumSet.Where(f1 => f1.OrderForum > forumset.OrderForum).ToList();
                foreach (ForumSet forum in forumToMoveDown)
                    forum.OrderForum -= 10;
            }

            db.ForumSet.Remove(forumset);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //
        // GET: /Forum/Forum/MoveUp/5

        [Authorize(Roles = "RoleAdminForum")]
        public ActionResult MoveUp(int id = 0)
        {
            ForumSet forumset = db.ForumSet.Find(id);
            if (forumset == null)
            {
                return HttpNotFound();
            }

            if (forumset.OrderForum == 10)
                return RedirectToAction("Index");

            var forumAbove = db.ForumSet.Where(f1 => f1.OrderForum == (forumset.OrderForum - 10)).First();
            forumAbove.OrderForum = forumset.OrderForum;
            forumset.OrderForum -= 10;

            if (ModelState.IsValid)
            {
                db.Entry(forumset).State = EntityState.Modified;
                db.Entry(forumAbove).State = EntityState.Modified;
                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        //
        // GET: /Forum/Forum/MoveDown/5

        [Authorize(Roles = "RoleAdminForum")]
        public ActionResult MoveDown(int id = 0)
        {
            ForumSet forumset = db.ForumSet.Find(id);
            if (forumset == null)
            {
                return HttpNotFound();
            }

            if (forumset.OrderForum == db.ForumSet.Max(f1 => f1.OrderForum))
                return RedirectToAction("Index");

            var forumBelow = db.ForumSet.Where(f1 => f1.OrderForum == (forumset.OrderForum + 10)).First();
            forumBelow.OrderForum = forumset.OrderForum;
            forumset.OrderForum += 10;

            if (ModelState.IsValid)
            {
                db.Entry(forumset).State = EntityState.Modified;
                db.Entry(forumBelow).State = EntityState.Modified;
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}